import arrow
import ast
import json
import datetime

from pymongo import MongoClient
from bson import ObjectId

from conf.settings import CLOUDMONITOR_MONGODB


# db = MongoClient(CLOUDMONITOR_MONGODB)['cloudmonitor']
db = MongoClient(host='localhost', port=27017)['cloudmonitor']
# db_oms = MongoClient('')['cloudmonitor']

arrow_now = arrow.utcnow()
uid_list = [item.get('uid') for item in db['balances'].find({'planExpireTime': {'$gt': arrow_now.datetime}})]


def get_username():
    username_list = [item.get('username') for item in db['users'].find({'_id': {'$in': uid_list}})]

    with open('./username.csv', 'w', encoding='utf-8') as f:
        f.writelines(','.join(username_list))


def insert_trade_log():
    with open('./trade_log.csv', 'r', encoding='utf-8') as f:
        trade_log = f.readlines()

    new_trade_log = []
    for item in trade_log:
        item = item.replace('\n', '')
        a = eval(item)
        new_trade_log.append(a)

    db['trade_log'].insert_many(new_trade_log)


def main():
    plans_key = [item.get('key') for item in db['packages'].find({'chargeType': 'plan'})]

    pipeline = [
        {'$match': {'uid': {'$in': uid_list}, 'isDelete': False, 'chargeType': 'additionPackage'}},
        {'$lookup': {'from': 'users', 'foreignField': '_id', 'localField': 'uid', 'as': 'user'}},
        {'$unwind': '$user'},
        {'$project': {'uid': 1, 'username': '$user.username', 'packId': 1, 'createTime': 1, 'expireTime': 1, 'number': 1}},
        {'$lookup': {'from': 'packages', 'foreignField': '_id', 'localField': 'packId', 'as': 'addition'}},
        {'$unwind': '$addition'},
        {'$project': {'username': 1, 'key': '$addition.key', 'createTime': 1, 'expireTime': 1, 'number': 1, 'packId': 1}},
    ]
    user_package_dict = {}
    for charge in db['charges'].aggregate(pipeline):
        user_package = user_package_dict.setdefault(charge['username'], {})

        pack_one = user_package.setdefault((charge['createTime'], charge['packId']), [])
        pack_one.append({
            'createTime': charge['createTime'],
            'number': charge['number'],
            'key': charge['key'],
            'expireTime': charge['expireTime']
        })

    new_user_pack_dict = {}
    for k, v in user_package_dict.items():
        _temp_list = []
        for _, _item_list in v.items():
            for _item in _item_list:
                _temp_list.append(_item)
                break
        new_user_pack_dict[k] = _temp_list

    add_list = []
    for item in db['trade_log'].find({
        'expire_time': {'$gt': arrow_now.datetime},
        'trade_status': 'TRADE_SUCCESS',
        'trade_product': {'$nin': plans_key, '$elemMatch': {'$regex': 'scanv'}},
    }):
        username = item['username']
        if not (exist_user_pack_list := new_user_pack_dict.get(username)):
            continue

        expire_time = item['expire_time']
        number = item['trade_amount']
        hours_prefix = 25

        for key in item['trade_product']:
            if 'scanv' not in key:
                continue

            checked = False
            for pack in exist_user_pack_list:
                expire_time_1 = pack['expireTime']
                number_1 = pack['number']

                if not (datetime.timedelta(hours=-hours_prefix) < (expire_time_1 - expire_time) < datetime.timedelta(hours=hours_prefix)):
                    continue

                if int(number) != int(number_1):
                    continue

                checked = True

            if not checked:
                add_list.append({
                    'username': item['username'],
                    'name': key,
                    'expireTime': item['expire_time'],
                    'num': item['trade_amount']
                })

    print(1)




if __name__ == '__main__':
    main()
